package cn.jdy.plugins.websocket;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.plugins.entity.Chat;
import cn.jdy.plugins.entity.RedPacket;
import cn.jdy.plugins.entity.VisitLog;
import cn.jdy.plugins.service.ChatService;
import cn.jdy.plugins.service.RedPacketService;
import cn.jdy.plugins.service.VisitLogService;

/**
 * @desc   websocket服务端处理器
 * @author ningqian
 * @date   2017-3-23
 */
public class WebsocketEndPoint extends TextWebSocketHandler {
	 public static final Map<String, WebSocketSession> users; //客户端对象
	 private static Long onlineCount = 0L;   //记录当前在线人数
	 
	 @Autowired
	 private ChatService chatService;
	 @Autowired
	 private RedPacketService redPacketService;
 	 @Autowired
	 protected HttpSession httpSession;
 	 @Autowired
 	 private VisitLogService visitLogService;
	
	 static {
		 users = new HashMap<String, WebSocketSession>();
	 }

	/**
	 * 建立连接后
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session)throws Exception {
		String uid = (String) session.getAttributes().get(Constants.WEBSOCKET_USERId);
        if (users.get(uid) == null) {
        	users.put(uid, session);
        	addOnlineCount(); // 在线数加1
        }
	}


	/**
	 * 处理客户端发来的消息
	 */
	@Override
	public void handleTextMessage(WebSocketSession session,TextMessage message) throws Exception {
		super.handleTextMessage(session, message);
		String liveId = (String) session.getAttributes().get(Constants.WEBSOCKET_LIVEID);
		String uid = (String) session.getAttributes().get(Constants.WEBSOCKET_USERId);
		String userNickName = (String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);
		String userHeadImg = (String) session.getAttributes().get(Constants.WEBSOCKET_USERHEADIMG);
		String userSex = (String) session.getAttributes().get(Constants.WEBSOCKET_USERSEX);

		 if(message.getPayloadLength()==0){
			 return;
		 }else{
			 //截取消息
			 String chatType = "1";  //消息类别1-文字，2-图片 3-红包消息
			 //消息内容
			 String msg = message.getPayload();      
			 if(msg.equals("lineCount")){
				 TextMessage textMessage = new TextMessage("10,"+getOnlineCount());
				 sendMessageToUsers(textMessage);
			 }else{
				 RedPacket red = redPacketService.findOne("orderNo",msg);
				 if(null != red){  //能查到红包 则为红包消息
					
					 
					 if(red.getRpType().equals("4")){
						 chatType = "4";//打赏信息
						 msg = red.getTotal() + ";" + red.getWishMsg();
					 }else{
						 chatType = "3";
						 msg = msg + ";" + red.getWishMsg();
					 }
			
				 }else{
					 if(msg.startsWith("/upload/confPic")){
						 chatType = "2";
					 }
				 }
				 
				 //记录消息
				 saveChat(liveId,uid,userNickName,userHeadImg,userSex,chatType,msg);
			 }
			
		 }
			 
	}
	
	/**
	 * 处理异常
	 */
    @Override  
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {  
        if(session.isOpen()){  
            session.close(); 
        }  

        Iterator<Entry<String, WebSocketSession>> it = users.entrySet().iterator();
        // 移除Socket会话
        while (it.hasNext()) {
            Entry<String, WebSocketSession> entry = it.next();
            if (entry.getValue().getId().equals(session.getId())) {
            	users.remove(entry.getKey());

            	subOnlineCount(); // 在线数减1
                break;
            }
        }
    }  
   
    /**
     * 关闭连接
     */
   @Override  
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {  
    	 Iterator<Entry<String, WebSocketSession>> it = users.entrySet().iterator();
         // 移除Socket会话
         while (it.hasNext()) {
             Entry<String, WebSocketSession> entry = it.next();
             if (entry.getValue().getId().equals(session.getId())) {
            	 
//         		saveVisitLog(${watchUser.liveId}, '${watchUser.openid }','${watchUser.nickname }','${watchUser.headimgurl }','${watchUser.sex}', "退出直播间", "2");
         	//添加退出记录
            String liveId = (String) session.getAttributes().get(Constants.WEBSOCKET_LIVEID);
      		String uid = (String) session.getAttributes().get(Constants.WEBSOCKET_USERId);
      		String userNickName = (String) session.getAttributes().get(Constants.WEBSOCKET_USERNAME);
      		String userHeadImg = (String) session.getAttributes().get(Constants.WEBSOCKET_USERHEADIMG);
     		String userSex = (String) session.getAttributes().get(Constants.WEBSOCKET_USERSEX);
    		VisitLog visitLog = new VisitLog();
    		visitLog.setLiveId(Long.valueOf(liveId));
    		visitLog.setUserOpenId(uid);
    		visitLog.setUserNickName(userNickName);
    		visitLog.setUserHeadImg(userHeadImg);
    		visitLog.setUserSex(userSex);
    		visitLog.setOperateDesc("退出直播间");
    		visitLog.setStatus("2");
    		visitLog.setCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
         	 visitLogService.save(visitLog);
         	VisitLog visitLog2 = new VisitLog();
    		visitLog2.setUserOpenId(uid);

    		visitLog2.setOperateDesc("观看直播");
    		//List<VisitLog> list=visitLogService.query(visitLog2);
    	   //    BaseLog.e(this.getClass(), "list的数："+list.size());
         //	 if(list.size()>0){  //直播离开时间
         	//	VisitLog  vlist=list.get(0);
         	//	vlist.setUpdateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
         	//	visitLogService.update(vlist);
         //	 }
            	 users.remove(entry.getKey());
            	 subOnlineCount(); // 在线数减1

                 break;
             }
         }  
    } 
	

    public boolean supportsPartialMessages() {
        return false;
    }
    
    
	/**
	 * 给所有在线用户发送消息
	 * 
	 * @param message
	 */
	public void sendMessageToUsers(final TextMessage message) {
		Iterator<Entry<String, WebSocketSession>> it = users.entrySet().iterator();
		if(getOnlineCount()>=1){  //当人数大于等于1时
			BaseLog.e(this.getClass(), "输出消息给在线人员......");
		}
    	BaseLog.e(this.getClass(), "是否进来it.hasNext()"+it.hasNext());
        // 多线程群发
        while (it.hasNext()) {
        	BaseLog.e(this.getClass(), "是否进来......");
            final Entry<String, WebSocketSession> entry = it.next();
 
            if (entry.getValue().isOpen()) {
            	BaseLog.e(this.getClass(), "来了吗.....");
              	BaseLog.e(this.getClass(), "msg"+message.getPayload());
            	BaseLog.e(this.getClass(), "msg"+message.toString());
         
              //   try {
			//		entry.getValue().sendMessage(message);
			//	} catch (IOException e) {
					// TODO Auto-generated catch block
				//	e.printStackTrace();
				//}
             new Thread(new Runnable() {
 
                    public void run() {
                        try {
                           	BaseLog.e(this.getClass(), "msgri"+entry.getValue().isOpen());
                            if (entry.getValue().isOpen()) {
                              	BaseLog.e(this.getClass(), "可以发送吗"+entry.getValue().getId());
                                entry.getValue().sendMessage(message);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
 
                }).start();
            }
 
        }
		
	}
	
	
	/**
     * 给某个用户发送消息
     * 
     * @param userName
     * @param message
     * @throws IOException
     */
    public void sendMessageToUser(String uid, TextMessage message)
            throws IOException {
        WebSocketSession session = users.get(uid);
        if (session != null && session.isOpen()) {
            session.sendMessage(message);
        }
    }
    
    /**
     * 记录消息
     */
    public void saveChat(String liveId,String uid,String userNickName,String userHeadImg,String userSex,String chatType,String message){
    	Chat chat = new Chat();
    	chat.setLiveId(Long.valueOf(liveId));
    	chat.setUserOpenId(uid);
    	chat.setUserNickName(userNickName);
    	chat.setUserHeadImg(userHeadImg);
    	chat.setUserSex(userSex);
    	chat.setChatType(chatType);
    	chat.setChatContent(message);
    	chat.setStatus("0");
    	String createTime = DateUtil.getCurrentDate(DateUtil._DEFAULT2);
    	chat.setCreateTime(createTime);
    	chatService.save(chat);
    	
    	//屏蔽脏字
    	String reg = "[艹|日|靠|槽|逼|草|婊|淫|骚]";
		String msg = message.replaceAll(reg, "*");
    	
    	String json = "{'liveId':"+liveId+",'userOpenId':'"+uid+"','userNickName':'"+userNickName+"','userHeadImg':'"+userHeadImg+"',"
    			+ "'chatType':'"+chatType+"','message':'"+msg+"','createTime':'"+createTime+"'}";
    	 
//    	String json = "{liveId:"+liveId+",userOpenId:'"+uid+"',userNickName:'"+userNickName+"',userHeadImg:'"+userHeadImg+"',"
//    			+ "chatType:'2',message:'"+message+"',createTime:'"+createTime+"'}";
    	//将客户端发送的信息输出给所有在线人员
    	TextMessage textMessage = new TextMessage(json);
    	sendMessageToUsers(textMessage);
    	
    }
    
    

    public static synchronized Long getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        WebsocketEndPoint.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
    	WebsocketEndPoint.onlineCount--;
    }


}
